﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace ProjectFootball.Foundation.Interfaces
{
    public static class _IHeaderEntity
    {
        public static TVersion GetApprovedVersion<TVersion>(this IHeaderEntity<TVersion> header, DateTime viewDate)
            where TVersion : IApprovableEntity
        {
            return header.GetApprovedVersions<TVersion>().Single(h => h.EffectiveFrom <= viewDate && h.EffectiveTo >= viewDate);
        }

        public static IEnumerable<TVersion> GetApprovedVersions<TVersion>(this IHeaderEntity<TVersion> header)
            where TVersion : IApprovableEntity
        {
            return header.Versions.Where(h => h.IsApproved);
        }

        public static void NormaliseVersionEffectiveDates<TVersion>(this IHeaderEntity<TVersion> header)
            where TVersion : IApprovableEntity
        {
            var versions = header.GetApprovedVersions<TVersion>();

            DateTime? lastEffectiveFrom = null;

            foreach (var item in versions.OrderByDescending(v => v.EffectiveFrom))
            {
                if (lastEffectiveFrom != null)
                    item.EffectiveTo = ((DateTime)lastEffectiveFrom).AddMilliseconds(-5);

                lastEffectiveFrom = item.EffectiveFrom;
            }
        }
    }
}
